package com.downloading.bezoyaapp;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.downloading.bezoyaapp.R;
import com.downloading.bezoyaapp.entities.Pregunta;
import com.downloading.bezoyaapp.entities.TipoPregunta;
import com.downloading.bezoyaapp.gcm.ServerUtilities;
import com.downloading.bezoyaapp.support.utils.Constraints;
import com.google.android.gcm.GCMRegistrar;

public class NewPregunta extends Activity {

	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;

	Spinner tipoPregunta;
	Button newFoto;
	Button savePregunta;
	TextView enunciado;
	ImageView foto;
	Uri fileUri;
	AsyncTask<Void, Void, Void> mRegisterTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_pregunta);

		// COMPROBAR REGISTRO GOOGLE + email.

		// GCMRegistrar.unregister(this);

		// PRUEBA PARA GCM
		Log.i("BezoyaApp", "Empezamos GCM");
		GCMRegistrar.checkDevice(this);
		Log.i("BezoyaApp", "Chequeamos device");
		GCMRegistrar.checkManifest(this);
		Log.i("BezoyaApp", "Chequeamos manifest");

		final String regId = GCMRegistrar.getRegistrationId(this);
		if (regId.equals("")) {
			// Automatically registers application on startup.
			Log.i("BezoyaApp", "Intentamos Registrar");
			GCMRegistrar.register(this, Constraints.SENDER_ID);
			Log.i("BezoyaApp", "Registrado");

		} else {
			// Device is already registered on GCM, check server.
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.
				Log.i("BezoyaApp", "Ya Registrado");

				Toast.makeText(this, "Ya Registrado", Toast.LENGTH_LONG).show();
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				Log.i("BezoyaApp", "ReRegistramos");
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						ServerUtilities.register(context, regId);
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}

		// FIN PRUEBA PARA GCM
		enunciado = (TextView) findViewById(R.id.newpregunta_enunciado_textbox);
		newFoto = (Button) findViewById(R.id.newpregunta_addfoto_button);
		foto = (ImageView) findViewById(R.id.newpregunta_fotoSacada_image);
		tipoPregunta = (Spinner) findViewById(R.id.newpregunta_tipopregunta_spinner);
		savePregunta = (Button) findViewById(R.id.newpregunta_guardarpregunta_button);

		newFoto.setOnClickListener(new OnButtonClick());
		savePregunta.setOnClickListener(new OnButtonClick());

		tipoPregunta.setAdapter(new ArrayAdapter<TipoPregunta>(this,
				android.R.layout.simple_spinner_item, TipoPregunta.values()));

	}

	@Override
	protected void onResume() {
		super.onResume();

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_new_pregunta, menu);
		return true;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// Image captured and saved to fileUri specified in the Intent
				/*
				 * Toast.makeText(this, "Image saved to:\n" + data.getData(),
				 * Toast.LENGTH_LONG).show();
				 */

				foto.setImageURI(fileUri);
			} else if (resultCode == RESULT_CANCELED) {
				// User cancelled the image capture
			} else {
				// Image capture failed, advise user
			}
		}
	}

	private class OnButtonClick implements OnClickListener {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.newpregunta_addfoto_button:

				// Vamos a sacar la foto
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

				fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

				// start the image capture Intent
				startActivityForResult(intent,
						CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
				break;

			case R.id.newpregunta_guardarpregunta_button:

				Pregunta pregunta = new Pregunta(0, enunciado.getText()
						.toString(), fileUri, TipoPregunta.SALUD);

				Intent intentBack = new Intent(NewPregunta.this,
						PreguntasRespuestas.class);
				Bundle bundle = new Bundle();
				intentBack.putExtras(bundle);

				startActivity(intentBack);
				break;
			}

		}

		private Uri getOutputMediaFileUri(int type) {
			return Uri.fromFile(getOutputMediaFile(type));
		}

		private File getOutputMediaFile(int type) {
			// To be safe, you should check that the SDCard is mounted
			// using Environment.getExternalStorageState() before doing this.

			File mediaStorageDir = new File(
					Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
					"MyCameraApp");
			// This location works best if you want the created images to be
			// shared
			// between applications and persist after your app has been
			// uninstalled.

			// Create the storage directory if it does not exist
			if (!mediaStorageDir.exists()) {
				if (!mediaStorageDir.mkdirs()) {
					Log.d("MyCameraApp", "failed to create directory");
					return null;
				}
			}

			// Create a media file name
			String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
					.format(new Date());
			File mediaFile;
			if (type == MEDIA_TYPE_IMAGE) {
				mediaFile = new File(mediaStorageDir.getPath() + File.separator
						+ "IMG_" + timeStamp + ".jpg");
			} else if (type == MEDIA_TYPE_VIDEO) {
				mediaFile = new File(mediaStorageDir.getPath() + File.separator
						+ "VID_" + timeStamp + ".mp4");
			} else {
				return null;
			}

			return mediaFile;
		}

	}
}
